package com.wocai.jrt.orgadmin.pay.action;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.vteba.utils.common.ExportExcel;
import com.vteba.utils.date.DateUtils;
import com.vteba.utils.json.FastJsonUtils;
import com.vteba.web.action.GenericAction;
import com.wocai.jrt.orgadmin.orders.bean.OrderReqBean;
import com.wocai.jrt.orgadmin.orders.bean.OrderResBean;
import com.wocai.jrt.orgadmin.orders.model.Orders;
import com.wocai.jrt.orgadmin.orders.service.spi.OrdersService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 订单审核Action
 * @author yinlei
 * @date 2015年11月19日 下午4:48:20
 */
@Controller
@RequestMapping("/orderAudit")
public class OrderAuditAction extends GenericAction<Orders> {
	private static final Logger LOGGER = LoggerFactory.getLogger(OrderAuditAction.class);
	
	@Inject
	private OrdersService ordersServiceImpl;
	
	@RequestMapping("/list")
	public String list(Orders orders) {
		return "orderAudit/list";
	}
	
	/**
	 * 查询需审核订单List，Json格式。
	 * 
	 * @param model
	 *            参数
	 * @return 订单List
	 */
	@ResponseBody
	@RequestMapping(value = "/query", method = RequestMethod.POST)
	public Map<String, Object> query(@RequestBody OrderReqBean model) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			model.setOrgId(UserUtils.getOrgId());
			model.setOrderBy("o.order_time desc");
			Date orderEnd = model.getOrderTimeEnd();
			if (orderEnd != null) {
				DateTime date = new DateTime(orderEnd);
				date = date.plusDays(1).minusMillis(1);
				model.setOrderTimeEnd(date.toDate());
			}
			LOGGER.info("获取需审核订单的model参数: [{}]",JSON.toJSONString(model));
			List<OrderResBean> list = ordersServiceImpl.getAuditOrderList(model);
			// 统计的时候，不需要分页
			model.setPage(null);
			long totalRecord = ordersServiceImpl.countAuditOrderByOrgId(model);

			if (LOGGER.isDebugEnabled()) {
				LOGGER.debug("order query success.");
			}

			// jQuery datatable 就是这样的参数，阿西吧
			// result.put("sEcho", user.getEcho());// 这个参数要回传，但是好像也不需要，阿西吧
			result.put("aaData", list); // 返回的数据
			result.put("iTotalRecords", totalRecord); // 总记录数
			result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("order query error, msg=[{}]", e.getMessage());
		}
		return result;
	}
	
	/**
	 * 导出Excel
	 * @param model 参数
	 * @param response HttpServletResponse
	 */
	@RequestMapping("/export")
	public String export(String params, HttpServletResponse response) {
		try {
			OrderReqBean model = FastJsonUtils.fromJson(params, OrderReqBean.class);
			model.setOrgId(UserUtils.getOrgId());
			
			Date orderEnd = model.getOrderTimeEnd();
			if (orderEnd != null) {
				DateTime date = new DateTime(orderEnd);
				date = date.plusDays(1).minusMillis(1);
				model.setOrderTimeEnd(date.toDate());
			}
			
			List<OrderResBean> list = ordersServiceImpl.getAuditOrderList(model);
			if (list == null || list.size() == 0) {
				list = new ArrayList<OrderResBean>();
			}
			List<Object[]> dataList = buildData(list);
			
			String[] titles = {"订单编号", "投资人", "投资人电话", "产品", "认购金额", "下单时间", "审核状态"};
			int[] columnWidths = {35, 10, 15, 30, 15, 20, 10};
			ExportExcel excel = new ExportExcel(titles, columnWidths, true);
			excel.setSheetName("订单审核列表");
			
			Workbook workbook = excel.toExcel(dataList);
			
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/octet-stream; charset=UTF-8");
			String fileName = "订单审核列表-" + DateUtils.toDateString("yyyyMMddHHmmss");
			response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8") + ".xlsx");
			OutputStream os = response.getOutputStream();
			workbook.write(os);
			
			os.flush();
			os.close();
			workbook.close();
			response.flushBuffer();
		} catch (Exception e) {
			
		}
		return null;
	}
	
	private List<Object[]> buildData(List<OrderResBean> list) {
		List<Object[]> result = new ArrayList<>();
		for (OrderResBean bean : list) {
			Object[] obj = new Object[7];
			obj[0] = bean.getOrderId();
			obj[1] = bean.getInvestorName();
			obj[2] = bean.getInvestorMobile();
			obj[3] = bean.getProductBriefName();
			obj[4] = bean.getOrderAmount();
			obj[5] = bean.getOrderTime();
			obj[6] = bean.getAuditState() == 1 ? "未审核" : bean.getAuditState() == 2 ? "审核未通过" : "审核已通过";
			
			result.add(obj);
		}
		return result;
	}

}
